<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test.js"></script>
<script src="../resources/common.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>

<script>
description("Test that keys can be derived from an HKDF key");

jsTestIsAsync = true;

kHkdfKey = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b";

var extractable = false;
var derivingKeyAlgorithm = {
    name: "HKDF",
    hash: "SHA-256",
    salt: new Uint8Array(),
    info: new Uint8Array()
};

Promise.resolve(null).then(function(result) {
    return crypto.subtle.importKey("raw", hexStringToUint8Array(kHkdfKey), "HKDF", extractable, ['deriveKey']);
}).then(function(result) {
    baseKey = result;

    return crypto.subtle.deriveKey(derivingKeyAlgorithm, baseKey, {name: "AES-GCM", length: 256}, extractable, ['encrypt']);
}).then(function(result) {
    derivedKey = result;

    shouldEvaluateAs("derivedKey.type", "secret");
    shouldEvaluateAs("derivedKey.extractable", extractable);
    shouldEvaluateAs("derivedKey.algorithm.name", "AES-GCM");
    shouldEvaluateAs("derivedKey.usages.join(',')", "encrypt");

    debug("\nTry to derive an HKDF key...");
    return crypto.subtle.deriveKey(derivingKeyAlgorithm, baseKey, "HKDF", extractable, ['deriveKey']);
}).then(failAndFinishJSTest, function(result) {
    logError(result);

    // Create an empty key and test deriving a key with it.
    return crypto.subtle.importKey("raw", new Uint8Array(), "HKDF", extractable, ['deriveKey']);
}).then(function(result) {
    emptyKey = result;

    shouldEvaluateAs("emptyKey.type", "secret");
    shouldEvaluateAs("emptyKey.extractable", extractable);
    shouldEvaluateAs("emptyKey.algorithm.name", "HKDF");
    shouldEvaluateAs("emptyKey.usages.join(',')", "deriveKey");

    return crypto.subtle.deriveKey(derivingKeyAlgorithm, emptyKey, {name: "AES-GCM", length: 256}, extractable, ['encrypt']);
}).then(function(result) {
    derivedKey = result;

    shouldEvaluateAs("derivedKey.type", "secret");
    shouldEvaluateAs("derivedKey.extractable", extractable);
    shouldEvaluateAs("derivedKey.algorithm.name", "AES-GCM");
    shouldEvaluateAs("derivedKey.usages.join(',')", "encrypt");
}).then(finishJSTest, failAndFinishJSTest);

</script>

</body>
</html>
